package com.example.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.ImportListener;
import com.example.common.Result;
import com.example.domain.Books;
import com.example.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.print.Book;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class BookController {

    @Autowired
    private BookService bookService;
    @Autowired
    private InformationController informationController;


    /*
    分页展示书籍
     */
    @GetMapping("/selectBookByPage")
    public Result selectBookByPage(@RequestParam(defaultValue = "") String name,
                                   @RequestParam Integer current,@RequestParam Integer size){
        Page<Books> books = bookService.selectBookByPage(name, current, size);
        return Result.success(books);
    }

    /**
     * 购买书籍，首先根据booid查到书籍，调用去修改information的余额，然后在Spend_list里添加购书记录
     */
    @GetMapping("/buyBookById")
    public Result buyBookById(@RequestParam Long bookId,@RequestParam Long userId){
        Books books = bookService.selectById(bookId);
        if(!informationController.updateBalance(books,userId)){
            return Result.error("余额不足");
        }
        return Result.success("购买成功");
    }

    /*
    管理员显示书籍
     */
    @GetMapping("/admin/selectbooklistByPage")
    public Result adminSelectbooklistByPage(@RequestParam(defaultValue = "") String name,
                                   @RequestParam Integer current,@RequestParam Integer size){
        Page<Books> books = bookService.selectBookByPage(name, current, size);
        return Result.success(books);
    }


    /*
    管理员添加书籍
     */
    @PostMapping("/addBook")
    public Result addUser(@RequestBody Books book){
        bookService.addBook(book);
        return Result.success("添加成功");
    }

    /*
    管理员修改书籍
     */
    @PostMapping("/editBook")
    public Result updateBook(@RequestBody Books book){
        bookService.updateBook(book);
        return Result.success("修改成功");
    }

    /*
    删除书籍
     */
    @GetMapping("/delBookById/{id}")
    public Result delBookById(@PathVariable Long id){
        bookService.delBookById(id);
        return Result.success("删除成功");
    }
/*
批量删除书籍
 */
    //    springMVC会将传递过来的数组通过JSON方式转换为List数组
    @PostMapping("/delBookByIds")
    public Result delBookByIds(@RequestBody List<Long> Ids){
        bookService.delBookByIds(Ids);
        return Result.success("删除成功");
    }

    //    上传图片
    @PostMapping("/uploadBookImg")
    public Result uploadFile(@RequestParam("file") MultipartFile file){
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "E:\\userPhoto\\"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 利用UUID生成唯一新文件名

        File dest = new File(filePath + fileName);
//        防止创建文件的时候，避免这个文件所在的文件夹不存在，然后抛出异常
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
//            将图片保存到磁盘
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String filename = "/static/" + fileName;
        String photo ="http://localhost:8080/static/"+fileName;
        return Result.success("上传图片成功",(Object) photo);
    }

    //    导出execl表格
    @GetMapping("/exportBooks")
    public void exportUser(HttpServletResponse response) throws IOException {
        List<Books> books = bookService.selectAll();
//        是客户端浏览器区分不同的数据
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String filename = URLEncoder.encode("Book信息表","UTF-8");
//        设置响应头，文件下载方式，以附件形式下载，文件类型根据后缀决定
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");
        ServletOutputStream out = response.getOutputStream();
        EasyExcelFactory.write(out, Books.class).sheet("书籍信息表").doWrite(books);
    }

    //    将execl表格的数据导入数据库
    @PostMapping("/importBooks")
    public Result importUser(MultipartFile file) throws Exception {
        List<Books> books = new ArrayList<>();
        // 获取上传的文件流
        InputStream inputStream = file.getInputStream();
        ImportListener importListener = new ImportListener(bookService);
        // 读取Excel
        EasyExcel.read(inputStream, Books.class, importListener).sheet().doRead();
        return Result.success();
    }
}
